package org.example.user.projects.web.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * write something please~
 *
 * @author huangrz
 * @since 2021/3/3
 **/
public class CharsetEncodingFilter implements Filter {

    /**
     * 编码字符集
     */
    private String encoding = null;

    private ServletContext servletContext;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("=== CharsetEncodingFilter init ====");
        // 从web.xml配置中获取编码字符集
        this.encoding = filterConfig.getInitParameter("encoding");
        this.servletContext = filterConfig.getServletContext();
        servletContext.log("当前设置的字符集为：" + encoding);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("=== CharsetEncodingFilter 执行 start ====");

        if (servletRequest instanceof HttpServletRequest) {
            servletResponse.setCharacterEncoding(encoding);
            servletRequest.setCharacterEncoding(encoding);
        }

        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("=== CharsetEncodingFilter 执行 end   ====");
    }

    @Override
    public void destroy() {
        System.out.println("=== CharsetEncodingFilter destroy ====");
    }
}
